package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;
import com.mock.ems.config.UserManager;

import java.util.*;

/**
 * 提现申请
 * @author whx
 * @date 2017/08/19
 */
public class WithdrawController extends Controller {
    public void index()  {
        renderJsp("/withdraw_list.jsp");
    }

    public void pagination() {
        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        StringBuilder sqlExceptSql = new StringBuilder(" from user_withdraw_record ");
        List<Object> params = new ArrayList<Object>();
        String selectSql = "select *";

        String orderNo = getPara("order_no", "");
        if (StringUtil.isNotEmpty(orderNo.trim())) {
            sqlExceptSql.append( " and order_no = ?");
            params.add(orderNo.trim());
        }

        int status = getParaToInt("status", -1);
        if (status != -1) {
            sqlExceptSql.append( " and status = ?");
            params.add(status);
        }

        sqlExceptSql.append(" order by submit_time desc ");

        Page<Record> recordList = Db.paginate(pageNumber, limit, selectSql, sqlExceptSql.toString(), params.toArray());

        if (CollectionUtil.isNotEmpty(recordList.getList())) {
            recordList.getList().forEach(item -> {
                Long userId = item.getLong("user_id");
                Record user = UserManager.getUser(userId);
                if(user == null){
                    user = Db.findById("user",userId);
                    if(user != null){
                        UserManager.setUser(user);
                    }
                }
                item.set("nick_name",user == null ? "未知" : user.get("nick_name"));
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    @Before(Tx.class)
    public void audit() {

        Long id = getParaToLong("id");
        if (null == id) {
            renderJson(new JsonResult().status("-1"));
            return;
        }
        Integer status = getParaToInt("status");
        if (null == status) {
            renderJson(new JsonResult().status("-2"));
            return;
        }

        Record withdrawRecord = Db.findById("user_withdraw_record",id);
        if (null == withdrawRecord) {
            renderJson(new JsonResult().status("-3"));
            return;
        }

        Double amount = withdrawRecord.getDouble("amount");
        if (status == 1) {
           String sql = "update user_withdraw_record set freeze_amount = freeze_amount - ?,status = 1 where id = ?";
            if (Db.update(sql,amount,id) > 0) {

                //插入资金流水
                Record user_funds_record = new Record();
                user_funds_record.set("user_id",withdrawRecord.getLong("user_id"))
                        .set("action","资金提现")
                        .set("order_no",withdrawRecord.get("order_no"))
                        .set("type",3)
                        .set("amount",-amount)
                        .set("create_time",new Date());
                if (!Db.save("user_funds_record",user_funds_record)) {
                    throw new RuntimeException("save user_funds_record error");
                }
                renderJson(new JsonResult().status("000"));
                return;
            }
        }else {
            String sql = "update user_withdraw_record set freeze_amount = freeze_amount - ?, status = 0 where id = ? ";
            if (Db.update(sql,amount,id) <=0 ) {
                renderJson(new JsonResult().status("-4"));
                return;
            }
            //更新用户账户
            Long user_id = withdrawRecord.getLong("user_id");
            String updateAccountSQL = "update user_account set balance = balance + ? where user_id = ? ";
            if (Db.update(updateAccountSQL,amount,user_id) <= 0) {
                throw new RuntimeException("update user_account fail.");
            }
        }

        renderJson(new JsonResult().status("000"));
    }
}
